<template>
  <view class="pageLayout">
    <u--form
      labelPosition="top"
      :model="form"
      :rules="rules"
      ref="MyForm"
      labelWidth="500rpx"
      :labelStyle="labelStyle"
    >
      <view class="base_info">
        <u-form-item required label="计划" borderBottom prop="nodeName">
          <u--input
            placeholder="请输入"
            :fontSize="fontSize"
            v-model="form.nodeName"
            border="none"
            disabledColor="#ffffff"
          ></u--input>
        </u-form-item>
        <u-form-item
          label="实际完成时间"
          prop="completionTime"
          borderBottom
          @click="showTimePickerFn('completionTime')"
        >
          <u--input
            v-model="form.completionTime"
            border="none"
            disabled
            disabledColor="#ffffff"
            placeholder="请选择"
            :inputAlign="inputAlign"
            :fontSize="fontSize"
            suffixIcon="arrow-right"
            :suffixIconStyle="{ color: '#c0c4cc' }"
          ></u--input>
        </u-form-item>
        <u-form-item label="进度说明" prop="nodeContent" borderBottom>
          <u--textarea
            placeholder="请输入"
            :fontSize="fontSize"
            v-model="form.nodeContent"
            border="none"
            :maxlength="60"
            height="100rpx"
            count
          ></u--textarea>
        </u-form-item>

        <u-form-item>
          <view class="labelStyle" style="font-size: 30rpx">阶段成果图片</view>
          <custom-upload
            v-model="fileList"
            :max-count="5"
            @change="handleFileChange"
          />
        </u-form-item>
      </view>
    </u--form>

    <view class="bot_btn">
      <view class="btn_width" ref="btnBox">
        <u-button
          class="btn"
          :loading="loading"
          @click="clickSubmit"
          :color="'#a22d27'"
          :customStyle="`color:#ffffff;`"
          >保存</u-button
        >
      </view>
    </view>

    <u-modal
      :show="showModel"
      :showConfirmButton="false"
      :showCancelButton="false"
    >
      <view class="slot-content">
        <view class="title">温馨提示</view>
        <view class="content"
          >检测到您当前为最后计划，<text style="color: #a22c26"
            >保存后无法再次进行修改</text
          >，是否确定继续操作？</view
        >
        <view class="btn_box">
          <view class="cancel" @click="showModel = false">取消</view>
          <view class="confirm" @click="submitForm">确定</view>
        </view>
      </view>
    </u-modal>

    <u-datetime-picker
      :show="showDatePicker"
      v-model="Date"
      mode="date"
      @confirm="changeDatePicker"
      @cancel="closeDatePicker"
      :minDate="minDay"
      :maxDate="maxDay"
      confirmColor="#a22d27"
      :immediateChange="true"
    ></u-datetime-picker>
    <mytoast ref="toastRef" />
  </view>
</template>
<script>
import store from "../../store/index";
import myPicker from "@/components/myPicker";
import customUpload from "@/components/customUpload.vue";
import mytoast from "@/components/mytoast.vue";
import multiPicker from "@/components/multiPicker";
import {
  commitApprove,
  queryApproveDetailByID,
  updateProcessNode,
  queryProcessNodeDetailByID,
} from "../api/approval/index";
import { getTwoYearsAgoTimestamp } from "@/utils/time";
export default {
  components: {
    myPicker,
    customUpload,
    mytoast,
    multiPicker,
  },

  data() {
    return {
      // imgUrl: "https://www.yinyaoit.com",
      id: "",
      index: "",
      isLast: "",
      status: "",
      Date: null,
      timeKey: "", //日期选择器绑定的key
      minDay: "",
      maxDay: "",
      loading: false,
      showReject: false,
      showDatePicker: false, //日期选择器
      showModel: false, //提示框
      fileList: [],
      labelStyle: {
        "font-size": "30rpx",
        "font-weight": "700",
      },
      fontSize: "26rpx",
      inputAlign: "left",
      form: {
        nodeName: "",
        nodeContent: "",
        completionTime: null,
        nodeImagePath: "",
      },
      detail: null,
      rules: {
        nodeName: [
          {
            type: "string",
            required: true,
            message: "请输入审批主题",
            trigger: ["blur"],
          },
        ],
        approveContent: [
          {
            type: "string",
            required: false,
            message: "请输入",
            trigger: ["blur"],
          },
        ],
      },
    };
  },
  computed: {
    hasLogin() {
      return this.$store.state.token && this.$store.state.token.length > 0;
    },
  },
  methods: {
    /**
     * 关闭时间选择器
     */
    closeDatePicker() {
      this.showDatePicker = false;
    },
    /**
     * 打开时间选择器
     * @param key 键值
     */
    showTimePickerFn(key) {
      if (this.status == "NotStarted") {
        this.$refs.toastRef.showToast({
          msg: "当前计划未开始",
          duration: 3000,
          position: "center",
        });
        return;
      }
      this.timeKey = key;
      this.showDatePicker = true;
    },
    /**
     * 获取时间选择范围
     */
    getDateSele() {
      const { todayZero, afterTomorrowZero } = this.getZeroTimestamps();
      this.maxDay = todayZero;
      // this.MaxTimestamp = afterTomorrowZero;
      // this.Date = todayZero;
    },
    /**
     * 获取当天和后天零点时间戳
     * @param {boolean} isUTC 是否使用UTC时间
     * @returns { todayZero: number, afterTomorrowZero: number }
     */
    getZeroTimestamps(isUTC = false) {
      const getZeroDate = () => {
        const date = new Date();

        date.setHours(0, 0, 0, 0);
        return date;
      };

      // 当天零点
      const todayZero = getZeroDate().getTime();

      // 明天零点
      const afterTomorrowDate = getZeroDate();
      afterTomorrowDate.setDate(afterTomorrowDate.getDate() + 1);
      const afterTomorrowZero = afterTomorrowDate.getTime();

      return { todayZero, afterTomorrowZero };
    },
    /**
     * 日期选择
     */
    changeDatePicker(val) {
      let date;
      date = this.formatTimestamp(val.value, "onlyDate");
      date = date + " 23:00:00";
      this.form[this.timeKey] = date;
      this.showDatePicker = false;
      console.log(this.form);
    },

    /**
     * 图片上传反馈
     * @param files 当前文件列表
     */
    handleFileChange(files) {
      console.log("当前文件列表:", files);
    },
    /**
     * 保存
     */
    clickSubmit() {
      if (this.isLast && this.form.completionTime != null) {
        this.showModel = true;
      } else {
        this.submitForm();
      }
    },

    /**
     * 表单提交
     */
    async submitForm() {
      // if (this.fileList.length == 0) {
      //   uni.showToast({
      //     title: "请上传审批图片",
      //     icon: "none",
      //     duration: 1500,
      //   });
      //   return;
      // }
      console.log(8848);
      let action = await this.$refs.MyForm.validate();
      if (action) {
        let imgArr = [];
        if (this.fileList.length >= 0) {
          imgArr = this.fileList.map((item) => {
            return item.path;
          });
        }

        let data = {
          ...this.form,
          nodeImagePath: imgArr.length > 0 ? imgArr.join(",") : "",
        };
        // console.log(data, "data");
        // return
        this.loading = true;
        if (this.form.completionTime == null) {
          let saveData = {
            form: {
              ...this.form,
              nodeImagePath: imgArr.length > 0 ? imgArr.join(",") : "",
            },
            index: this.index,
          };
          // return
          const pages = getCurrentPages(); //获取页面栈
          const beforePage = pages[pages.length - 2]; //前一个页面
          console.log(beforePage, "beforePage");
          beforePage.$vm.save(saveData); //前一个页面方法
          uni.navigateBack();
        } else {
          data = {
            processNodeID: this.form.processNodeID,
            nodeNumber: this.form.nodeNumber,
            nodeName: this.form.nodeName,
            completionTime: this.form.completionTime,
            nodeContent: this.form.nodeContent,
            nodeImagePath: imgArr.length > 0 ? imgArr.join(",") : "",
          };

          updateProcessNode(data)
            .then((res) => {
              this.loading = false;
              this.showModel = false;
              this.$refs.toastRef.showToast({
                msg: "保存成功",
                duration: 3000,
                position: "center",
              });
              const pages = getCurrentPages(); //获取页面栈
              const beforePage = pages[pages.length - 2]; //前一个页面
              console.log(beforePage, "beforePage");
              beforePage.$vm.getDetail(); //前一个页面方法
              setTimeout(() => {
                uni.navigateBack();
              }, 1000);
            })
            .catch((e) => {
              this.loading = false;
              this.$refs.toastRef.showToast({
                msg: e.data.detail,
                duration: 3000,
                position: "center",
              });
            });
        }

        console.log(this.form, "this.form");
      } else {
        uni.showToast({ title: "请完善表单", icon: "none" });
        return false;
      }
    },

    /**
     * 获取详情
     */
    getInfo() {
      queryProcessNodeDetailByID({ processNodeID: this.id }).then((res) => {
        console.log(res);
        this.form = res.data;
        // this.form.approveTopic = res.data.approveTopic;
        // this.form.approveContent = res.data.approveContent;
        // this.form.approveImage = res.data.approveImage;
        // this.form.approveID = res.data.approveID;
        // this.detail = res.data;
        if (res.data.nodeImagePath) {
          this.fileList = res.data.nodeImagePath.split(",").map((item) => {
            return {
              path: item,
              url: this.imgUrl + "/" + item,
              status: "success",
            };
          });
        }
      });
    },
  },
  onLoad(options) {
    this.id = options.id;
    this.index = options.index;
    this.isLast = Number(options.isLast);
    this.status = options.status;
    if (this.id) {
      this.getInfo();
    }
  },
  onShow() {
    this.minDay = getTwoYearsAgoTimestamp();
    this.getDateSele();
  },
  onReady() {
    //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
    this.$refs.MyForm.setRules(this.rules);
  },
  /**
   * 上拉加载更多
   */
  onReachBottom() {},
};
</script>
<style>
page {
  background-color: #ffffff;
}
</style>

<style lang="scss" scoped>
.pageLayout {
  padding: 24rpx;
  padding-bottom: 80rpx;
}
.base_info {
  background-color: #ffffff;
  padding: 24rpx;
  box-sizing: border-box;
  border-radius: 8rpx;
  margin-bottom: 24rpx;
}
.labelStyle {
  margin-bottom: 24rpx;
  font-weight: 700;
  font-size: 26rpx;
}
.submit-container {
  margin-top: 40rpx;
  padding: 20rpx;
  background-color: #f5f7fb;
}

.info_box {
  width: 670rpx;
  background: #ffffff;
  border-radius: 8rpx;
  margin-top: 24rpx;
  padding: 24rpx 40rpx;
  box-sizing: border-box;
  position: relative;
  .editIcon {
    position: absolute;
    top: 24rpx;
    right: 24rpx;
    padding: 10rpx;
    background: #e7f8fc;
    border-radius: 14rpx;
    display: flex;
    align-items: center;
    view {
      font-size: 20rpx;
      margin-left: 3rpx;
      line-height: 15rpx;
    }
  }
  .reloadIcon {
    background: #fbe6e8;
  }
  .info_title {
    font-size: 20rpx;
    color: #1c1b2680;
    display: flex;
    align-items: center;
    view {
      margin-left: 10rpx;
    }
  }
  .info_name {
    font-size: 24rpx;
    color: #1c1b26;
    margin-top: 18rpx;
    margin-bottom: 32rpx;
    font-weight: 700;
  }
}
.pop_box {
  height: 80vh;
}
::v-deep .u-textarea__count {
  color: #c8c9cc !important;
}
.slot-content {
  text-align: center;
  .title {
    font-size: 30rpx;
    color: #969799;
    margin-bottom: 32rpx;
  }
  .content {
    color: #000000;
    font-size: 32rpx;
    font-weight: bold;
    line-height: 56rpx;
  }
  .btn_box {
    display: flex;
    justify-content: space-around;
    margin-top: 60rpx;
    .cancel {
      width: 260rpx;
      height: 88rpx;
      line-height: 80rpx;
      text-align: center;
      border-radius: 12rpx;
      color: #000;
      background-color: #f5f5f5;
    }
    .confirm {
      width: 260rpx;
      height: 88rpx;
      line-height: 80rpx;
      text-align: center;
      border-radius: 12rpx;
      color: #fff;
      background-color: #a22c26;
    }
  }
}
.bot_btn {
  position: relative;
  // background-color: #d52227;
  border-top: 1rpx solid #801c1b26;
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  margin-top: 40rpx;
  // box-shadow: #a5a5a5 0px 0px 6px;
  padding: 20rpx;
  padding-bottom: 50rpx;
  background-color: white;
  box-sizing: border-box;
  .btn_width {
    margin: 0 auto;
    display: flex;
    justify-content: space-between;
  }
}
</style>
